package com.miniapi.api.controllers;

import java.util.Map;

import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

import com.miniapi.api.common.YBLQRCodeReader;

import ybl.wechat.WeChatService;
import ybl.wechat.WeChatWeb;

@RestController
@RequestMapping("/api/wxweb")
public class WxWebController {

    @GetMapping("/echo")
    public String echo(@RequestParam Map<String, String> allParams) {
        System.out.println(allParams);
        return "echo: " + allParams.toString();
    }

    @GetMapping("/getAccessToken")
    public RedirectView checkServer(@RequestParam Map<String, String> allParams) {
        JSONObject jsonObject = WeChatWeb.getAccessToken(allParams.get("code"));
        String openId = jsonObject.getString("openid");
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://10.0.162.231:3000?id=" + openId);
        return redirectView;
    }

    /**
     * 根据openid获取二维码
     * 
     * @throws Exception
     */
    @GetMapping("/getQrCodeByOpenId")
    public String getQrCodeByOpenId(@RequestParam Map<String, String> allParams) throws Exception {
        String qrCodelink = WeChatService.createTemporaryParametricQRCode(allParams.get("openid"), 2592000);
        String qrcode = YBLQRCodeReader.decodeQRCodeFromURL(qrCodelink);
        JSONObject result = new JSONObject();
        result.put("qrcode", qrcode);
        System.out.println(result);
        return result.toString();
    }
}